<?php


namespace app\api\service;


use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use EasyWeChat\Factory;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class WxNotify
{
    public function NotifyProcess()
    {
        $config = [
            'app_id' => config('wx.app_id'),
            'mch_id' => config('wx.mch_id'),
            'secret' => config('wx.app_secret'),
            'key' => 'signatesussdfsdfsfasdadaddfsdfre',
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
        ];

        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            // 你的逻辑
            if ($message['result_code'] == 'SUCCESS') {
                $orderNo = $message['out_trade_no'];
                Db::startTrans();
                try {
                    $order = OrderModel::where('order_no', $orderNo)->find();
                    if ($order->status == 1) {
                        $stockStatus = (new OrderService())->checkOrderStock($order->id);
                        if ($stockStatus['pass']) {
                            //更新订单状态
                            $this->updateOrderStatus($order->id, true);
                            //减库存
                            $this->reduceStock($stockStatus);
                        } else {
                            $this->updateOrderStatus($order->id, false);
                        }
                    }
                    Db::commit();
                    return true;
                } catch (Exception $e) {
                    Db::rollback();
                    Log::error($e);
                    return false;
                }
            } else {
                //让微信不要返回回调消息
                return true;
            }
            // 或者错误消息
//            $fail('Order not exists.');
        });

        $response->send();
    }

    private function reduceStock($stockStatus)
    {
        foreach ($stockStatus as $value) {
            Product::where('id', $value['id'])->dec('stock', $value['count']);
        }
    }

    private function updateOrderStatus($orderID, $success)
    {
        $status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        OrderModel::where('id', $orderID)->update(['status' => $status]);
    }
}